package com.mmall.controller.backend;


import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.ICategoryService;
import com.mmall.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/manage/category")
public class CategoryManageController {

    @Autowired
    private IUserService iUserService;

    private ICategoryService iCategoryService;

    @RequestMapping("add_caregory.do")
    @ResponseBody
    public ServerResponse addCategory(HttpSession session, String categoryName,
                                      @RequestParam(value = "parenId", defaultValue = "0") Integer parentId) {
        User user = (User) session.getAttribute(Const.CREATE_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登陆请登录");
        }
        //检验是否是管理员
        if (iUserService.checkAdminRole(user).isSuccess()) {
            //是管理员
            return iCategoryService.addCategory(categoryName, parentId);
        } else {
            return ServerResponse.createByMessage("您不是管理员无权操作");
        }
    }

    @RequestMapping("set_category_name.do")
    @ResponseBody
    public ServerResponse setCategoryName(HttpSession session, Integer categoryId, String categoryName) {
        User user = (User) session.getAttribute(Const.CREATE_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登陆，请登录");
        }
        if (iUserService.checkAdminRole(user).isSuccess()) {
            //是管理员有权限更新分类名称
            return iCategoryService.updateCategoryName(categoryId, categoryName);
        } else {
            return ServerResponse.createByErrorMessage("没有权限需要管理员登陆");
        }
    }

    @RequestMapping("get_category.do")
    @ResponseBody
    public ServerResponse getChildrenrParllelCategory(HttpSession session, @RequestParam(value = "category", defaultValue = "0") Integer cateGoryId) {
        User user = (User) session.getAttribute(Const.CREATE_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登陆，请登陆");
        }
        if (iUserService.checkAdminRole(user).isSuccess()) {
            //是管理员有权限更新分类名称
            return iCategoryService.getChildrenParallelCategory(cateGoryId);
        } else {
            return ServerResponse.createByErrorMessage("没有权限需要管理员登陆");
        }
    }

//    public ServerResphonse getCategoryAndDeepChildrenCatergory()

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }


}

